package lib.bone.admin.controller.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lib.bone.access.config.cycle.NepuCycle;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.constant.SubjectTypeConst;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.dict.entity.NepuSubjectDict;
import lib.bone.access.module.dict.entity.NepuTopicDict;
import lib.bone.access.module.dict.impl.SubjectDictServiceImpl;
import lib.bone.access.module.dict.impl.TopicDictServiceImpl;
import lib.bone.admin.controller.system.dto.SubjectImportDTO;
import lib.bone.admin.controller.system.dto.TopicImportDTO;
import lib.bone.audit.workload.attach.ResearchAttach;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.utils.JsonUtil;
import lib.bone.ext.draft.NepuDraft;
import lib.bone.ext.draft.NepuDraftService;
import lib.bone.nepudata.domain.dto.topic.NepuTopicAddDTO;
import lib.bone.nepudata.domain.entity.NepuSubject;
import lib.bone.nepudata.domain.entity.NepuTopic;
import lib.bone.nepudata.service.impl.NepuSubjectServiceImpl;
import lib.bone.nepudata.service.impl.NepuTopicServiceImpl;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.module.iojob.constant.JobStatusConst;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.domain.IOLog;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
public class SubjectListener extends AnalysisEventListener<SubjectImportDTO> {

    /**
     * 文件父路径
     */
    String fileParentPath;
    /**
     * 周期ID
     */
    String cycleId;
    /**
     * 父周期ID
     */
    String parentCycleId;
    /**
     * 任务ID
     */
    String ioJobId;

    NepuCycle nepuCycle;
    /**
     * 用户服务
     */
    NepuSubjectServiceImpl nepuSubjectService;

    SubjectDictServiceImpl dictService;;

    SysUserService sysUserService;
    /**
     * 导入导出服务
     */
    IOJobService ioJobService;

    NepuDraftService draftService;

    NepuWorkloadService workloadService;
    /**
     * 操作日志
     */
    List<IOLog> logs = new ArrayList<>();

    DictServiceCtl dictServiceCtl;

    public SubjectListener(SysUserService userService, IOJobService ioJobService, NepuSubjectServiceImpl nepuSubjectService, String cycleId, String parentCycleId, String ioJobId, String fileParentPath,  SubjectDictServiceImpl dictService, NepuCycle nepuCycle,  NepuWorkloadService workloadService) {
        this.sysUserService = userService;
        this.nepuSubjectService = nepuSubjectService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.parentCycleId = parentCycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
        this.dictService = dictService;
        this.nepuCycle = nepuCycle;
        this.workloadService = workloadService;
    }

    public String buildAttach(NepuSubject subject, NepuSubjectDict nepuSubjectDict) {
        ResearchAttach attach = new ResearchAttach();
        attach.setResearchId(subject.getId());
        attach.setResearchName(subject.getSubjectName());
        attach.setDictId(nepuSubjectDict.getId());
        attach.setDictName(nepuSubjectDict.getSubjectType());
        attach.setResearchLevel(nepuSubjectDict.getSubjectLevel());
        attach.setResearchType(ResearchTypeConst.SUBJECT);
        return JsonUtil.obj2String(attach);
    }




    @Override
    public void invoke(SubjectImportDTO subjectImportDTO, AnalysisContext analysisContext) {

        List<NepuSubject> subjects = nepuSubjectService.findByCode(subjectImportDTO.getSubjectCode());
        if (subjects.size()>0) {
            log.info("{}:横向课题信息已存在,课题编码:{}", subjectImportDTO.getSubjectName(),subjectImportDTO.getSubjectCode());
            return;
        }
        NepuSubject subject = new NepuSubject();
        BeanUtil.copyProperties(subjectImportDTO,subject,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        Optional<SysUser> sysUserOp  = sysUserService.findByUserName(subjectImportDTO.getUsedrName());
        if(!sysUserOp.isPresent()){
            log.info("人员信息不存在:{},工号:{}",subjectImportDTO.getLeader());
            return;
        }
        subject.setLeaderId(sysUserOp.get().getId());
        //获取在研时间，转换格式
        Date startDate = subjectImportDTO.getStartDate();
        Date endDate = subjectImportDTO.getEndDate();
        subject.setStartDate(startDate);
        subject.setEndDate(endDate);
        //添加项目成员
        List<String> list = new ArrayList<>();
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId1())) {
            list.add(subjectImportDTO.getParticipateId1());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId2())) {
            list.add(subjectImportDTO.getParticipateId2());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId3())) {
            list.add(subjectImportDTO.getParticipateId3());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId4())) {
            list.add(subjectImportDTO.getParticipateId4());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId5())) {
            list.add(subjectImportDTO.getParticipateId5());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId6())) {
            list.add(subjectImportDTO.getParticipateId6());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId7())) {
            list.add(subjectImportDTO.getParticipateId7());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId8())) {
            list.add(subjectImportDTO.getParticipateId8());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId9())) {
            list.add(subjectImportDTO.getParticipateId9());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId10())) {
            list.add(subjectImportDTO.getParticipateId10());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId11())) {
            list.add(subjectImportDTO.getParticipateId11());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId12())) {
            list.add(subjectImportDTO.getParticipateId12());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId13())) {
            list.add(subjectImportDTO.getParticipateId13());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId14())) {
            list.add(subjectImportDTO.getParticipateId14());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId15())) {
            list.add(subjectImportDTO.getParticipateId15());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId16())) {
            list.add(subjectImportDTO.getParticipateId16());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId17())) {
            list.add(subjectImportDTO.getParticipateId17());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId18())) {
            list.add(subjectImportDTO.getParticipateId18());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId19())) {
            list.add(subjectImportDTO.getParticipateId19());
        }
        if (StrUtil.isNotEmpty(subjectImportDTO.getParticipateId20())) {
            list.add(subjectImportDTO.getParticipateId20());
        }
        if (list.size()!=0){
            //添加参与成员
            List<SysUser> list1 = sysUserService.findByUserNames(list);
            List<Long> idList = new ArrayList<>();
            for (SysUser sysUser : list1) {
                idList.add(sysUser.getId());
            }
            subject.setUserIdList(idList);

        }
        NepuSubject nepuSubject = nepuSubjectService.saveOne(subject);
        NepuWorkload nepuWorkload = new NepuWorkload();
        // 设置工作量来源 -- 申请
        nepuWorkload.setWorkloadSource(WorkloadSourceConst.APPLY);
        // 设置工作量类型 -- 科研工作量
        nepuWorkload.setWorkloadType(WorkloadTypeConst.RESEARCH);
        // 设置获取工作量用户ID
        nepuWorkload.setUserId(sysUserOp.get().getId());
        //获取科研项目Id
        nepuWorkload.setLinkId(nepuSubject.getId());
        //设置备注信息
        nepuWorkload.setRemark("["+nepuCycle.getCycleName()+"]"+"导入横向课题");
        //设置工作量可分配
        nepuWorkload.setWorkloadLock(2);
        // 获取工作量所在周期 -- 从科研项目中提取
        nepuWorkload.setCycleId(nepuCycle.getId());
        nepuWorkload.setParentId(nepuCycle.getId());
        Optional<NepuSubjectDict> subjectdictOp = dictService.calcDict(subjectImportDTO.getSubjectType(), subjectImportDTO.getFunds());
        if (!subjectdictOp.isPresent()){
            log.info("横向课题词典不存在:{},{}", subjectImportDTO.getSubjectType(),subjectImportDTO.getFunds());
            return;
        }
        NepuSubjectDict dict = subjectdictOp.get();
        // 具体赋分规则
        if(nepuSubject.getSubjectType().equals(SubjectTypeConst.NATURAL)){
            if (nepuSubject.getFunds()<500){
                String str = String.format("%.2f",nepuSubject.getFunds());
                nepuSubject.setWorkload(Double.valueOf(str));
            }else {
                nepuSubject.setWorkload(500.0);
            }
        }else {
            if (nepuSubject.getFunds()<2){
                int i = (int)(nepuSubject.getFunds()/0.2);
                if (nepuSubject.getFunds()>=0.2){
                    double d = nepuSubject.getFunds() % 0.2;
                    if (d > 0){
                        i = i + 1;
                    }
                }else {
                    i = 1;
                }
                nepuSubject.setWorkload(Double.valueOf(i));
            }else {
                nepuSubject.setWorkload(dict.getWorkloadMax());
            }
        }
        // 设置工作量级别
        String level = dict.getSubjectLevel();
        nepuWorkload.setWorkloadLevel(level);
        //工作量计算
        nepuWorkload.setWorkload(nepuSubject.getWorkload());
        // 设置使用工作量为 0 用尽标识为 0
        nepuWorkload.setUsedWorkload(0.0);
        nepuWorkload.setUsedUp(0);
        // 设置工作量附加信息
        String attach = buildAttach(nepuSubject, dict);
        nepuWorkload.setWorkloadAttach(attach);
        // 设置锁等级为 2
        nepuWorkload.setWorkloadLock(2);
        workloadService.saveOne(nepuWorkload);
        System.out.println("横向课题保存成功！"+nepuSubject+"------"+"信息为："+nepuWorkload);

    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Optional<IOJob> ioJobOp = ioJobService.getById(ioJobId);
        if (!ioJobOp.isPresent()) {
            log.error("导入任务丢失");
            return;
        }
        IOJob ioJob = ioJobOp.get();
        String filePath = fileParentPath+ File.separator+ioJob.getId()+File.separator+"log.xlsx";
        FileUtil.touch(filePath);
        EasyExcel.write(filePath,IOLog.class).sheet("sheet").doWrite(logs);

        ioJob.setJobStatus(JobStatusConst.FINISHED);
        ioJob.setLogFilePath(filePath);
        ioJobService.updateOne(ioJob);
        log.info("横向课题导入完成");
    }
}
